package com.carsa.blackberry.util;

import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.WLANInfo;

/**
 * @author Nahuel Barrios.
 * @since 10/08/2010.
 * @version 1.0
 */
public class DeviceUtil {

    public static final String PARAMETER_INTERFACE      = "interface";
    public static final String PARAMETER_DEVICESIDE     = "deviceside";
    public static final String PARAMETER_CONNECTION_UID = "ConnectionUID";

    public static final String PARAMETER_VALUE_TRUE     = "true";
    public static final String PARAMETER_VALUE_WIFI     = "wifi";
    public static final String PARAMETER_VALUE_FALSE    = "false";

    /**
     * @return true cuando la aplicacion tiene una conexion a su disposicion. Si no existe ninguna conexion, retorna
     *         false.
     */
    public static boolean hasConnection() {
	String connectionMethod = getConnectionMethodParameter();

	if (true)
	    return true;// TODO : Functionality : borrar esto, esta asi porque hay que probar este metodo desde la BB
	// para ver como anda.

	// Si el metodo de conexion es distinto de deviceside=false entonces quiere decir que SI tiene una conexion
	// disponible.
	if (!connectionMethod.equalsIgnoreCase(getParameterFor(PARAMETER_DEVICESIDE, PARAMETER_VALUE_FALSE)))
	    return true;

	return false;
    }

    /**
     * @return El tipo de conexion que tiene disponible el dispositivo.
     */
    public static String getConnectionMethodParameter() {
	String connectionParameters = "";
	if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
	    // Connected to a WiFi access point
	    connectionParameters = getParameterFor(PARAMETER_INTERFACE, PARAMETER_VALUE_WIFI);
	} else {
	    int coverageStatus = CoverageInfo.getCoverageStatus();
	    ServiceRecord record = getWAP2ServiceRecord();

	    if (record != null && (coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
		// Have network coverage and a WAP 2.0 service book record
		connectionParameters = getParameterFor(PARAMETER_DEVICESIDE, PARAMETER_VALUE_TRUE)
		        + getParameterFor(PARAMETER_CONNECTION_UID, record.getUid());

	    } else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
		// Have an MDS service book and network coverage
		connectionParameters = getParameterFor(PARAMETER_DEVICESIDE, PARAMETER_VALUE_FALSE);

	    } else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
		// Have network coverage but no WAP 2.0 service book record
		connectionParameters = getParameterFor(PARAMETER_DEVICESIDE, PARAMETER_VALUE_TRUE);
	    }
	}

	return connectionParameters;
    }

    /**
     * @return
     */
    private static ServiceRecord getWAP2ServiceRecord() {
	ServiceBook sb = ServiceBook.getSB();
	ServiceRecord[] records = sb.getRecords();

	for (int i = 0; i < records.length; i++) {
	    String cid = records[i].getCid().toLowerCase();
	    String uid = records[i].getUid().toLowerCase();
	    if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1) {
		return records[i];
	    }
	}

	return null;
    }

    /**
     * @param parameterName
     *            El nombre del parametro.
     * @param parameterValue
     *            El valor que toma el parametro.
     * @return Un {@link String} correspondiente en base al parameterName y al parameterValue para formar un parametro.
     */
    private static String getParameterFor(String parameterName, String parameterValue) {
	return parameterName + "=" + parameterValue;
    }

}
